﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Microsoft.Win32;
using System.Security.Permissions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
//必需  
using System.Xml;
//用于利用操作XML文件的方式更新配置文件  
namespace gerenxinxi
{
    public partial class frm_loading : Form
    {
        public FileStream fs = null;
        public FileStream fs1 = null;
        public String addre = "192.168.253.1";//网站IP
        public String userid = "";
        public frm_loading()
        {
            InitializeComponent();
        }

        private void enter_Click(object sender, EventArgs e)
        {
            String dl="";
            Dictionary<String, String> dic=null;
            if (string.Empty != username.Text.Trim() && password.Text.Trim() != String.Empty)
            {
                String address = "http://" + addre + "/onlinetest/userInfo";
                Dictionary<String, String> dmap = new Dictionary<string, string>();
                dmap.Add("username", username.Text.Trim());
                dmap.Add("userpass", password.Text.Trim());
                dmap.Add("usertype", "2");
                String dataStream = "";
                try
                {
                    dataStream = Utils.HttpPost(address, dmap);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("网络故障或服务器异常。");
                    Console.WriteLine(ex);
                    return;
                }
                dataStream = (dataStream == null ? "" : dataStream);
                try
                {
                    String decstring = Base64.DecodeBase64(dataStream);
                    dic = Utils.getFromJson(decstring);
                    Console.WriteLine(decstring);

                    String time;

                    Boolean f1 = dic.TryGetValue("time", out time);
                    Boolean f2 = dic.TryGetValue("loginreturn", out dl);
                    Console.WriteLine("shuchu : " + time + " " + dl + "f1:" + f1 + " f2:" + f2 + " " + dic.Count);
                    Console.WriteLine(decstring);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请检查网络设置和网站IP。");
                }
                if (dic != null)
                {
                    if (dl.Equals("false"))
                    {
                        String info = "";
                        dic.TryGetValue("info", out info);
                        MessageBox.Show(info);
                    }
                    else
                    {
                        //登陆成功后的操作
                        dic.TryGetValue("userid", out userid);
                        main index = new main();
                        index.username = username.Text.Trim();
                        index.password = password.Text.Trim();
                        index.ip = addre;
                        index.userid = this.userid;

                        index.uname = username.Text.Trim();
                        index.Visible = true;
                        index.Show();
                        this.Hide();
                    }
                }
            }
        }

        private void exit1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void frm_loading_Load(object sender, EventArgs e)
        {
            //读取配置文件中的ip配置
            String ipstr=ConfigurationManager.AppSettings["ipadd"];
            if (IPPre.IsIPAddress(ipstr))
            {
                addre = ipstr;
            }
            else {
                MessageBox.Show("请双击登陆框，设置IP地址");
            }

            //以独占方式打开文件  
            fs = new FileStream("C:\\Windows\\inf\\usbstor.inf", FileMode.Open, FileAccess.Read, FileShare.None);
            fs1 = new FileStream("C:\\Windows\\inf\\usbstor.PNF", FileMode.Open, FileAccess.Read, FileShare.None);

            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                // 修改注册表  
               Boolean fla= RegToStopUSB();
               if (fla == false)
               {
                   DialogResult result = MessageBox.Show("应用程序未能成功启动，请重新安装，或者关闭安全软件。", "警告", MessageBoxButtons.OK);
                   switch (result)
                   {
                       case DialogResult.OK:
                           Application.Exit();
                           break;
                       case DialogResult.Cancel:
                           break;
                   }
               }
               else {
                   Console.WriteLine("已禁用注册表");               
               }
                //RegToRunUSB();
                //Console.WriteLine("已启用注册表");
                //MessageBox.Show("已启用外接USB存储设备功能。");
            }
            else
            {
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; // 获取当前可执行文件的路径及文件名   
                ////以下 Args 为启动本程序的对应的参数  
                //startInfo.Arguments = String.Join(" ", Args);
                //startInfo.Verb = "runas";
                //System.Diagnostics.Process.Start(startInfo);
                Console.WriteLine(System.Windows.Forms.Application.ExecutablePath);
            }  
        }
        /// <summary>  
        /// 通过注册表启用USB  
        /// </summary>  
        /// <returns></returns>  
        public bool RegToRunUSB()
        {
            try
            {
                RegistryKey regKey = Registry.LocalMachine; //读取注册列表HKEY_LOCAL_MACHINE  
                string keyPath = @"SYSTEM\CurrentControlSet\Services\USBSTOR"; //USB 大容量存储驱动程序  
                RegistryKey openKey = regKey.OpenSubKey(keyPath, true);
                openKey.SetValue("Start", 3); //设置键值对（3）为开启USB（4）为关闭  
                openKey.Close(); //关闭注册列表读写流  
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
        }

        /// <summary>  
        /// 通过注册表禁用USB  
        /// </summary>  
        /// <returns></returns>  
        public bool RegToStopUSB()
        {
            try
            {
                RegistryKey regKey = Registry.LocalMachine;
                string keyPath = @"SYSTEM\CurrentControlSet\Services\USBSTOR";
                RegistryKey openKey = regKey.OpenSubKey(keyPath, true);
                openKey.SetValue("Start", 4);
                openKey.Close();
                //检测是否已修改
                RegistryKey masterKey = Registry.LocalMachine.CreateSubKey(@"SYSTEM\CurrentControlSet\Services\USBSTOR");
                if (masterKey == null)
                {
                    Console.WriteLine("Null Masterkey!");
                }
                else
                {
                    Console.WriteLine("Start:{0}", masterKey.GetValue("Start"));
                    if (!masterKey.GetValue("Start").ToString().Equals("4")) {
                        Console.WriteLine("未能修改成功");
                            DialogResult result = MessageBox.Show("应用程序未能成功启动，请重新安装，或者关闭安全软件。", "警告", MessageBoxButtons.OK);
                            switch (result)
                            {
                                case DialogResult.OK:
                                    Application.Exit();
                                    break;
                                case DialogResult.Cancel:
                                    break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("禁用注册表成功。");
                        }
                }
                masterKey.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
        }

        private void frm_loading_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            IPPre peizhi = new IPPre();
            peizhi.ShowDialog();
                if (peizhi.Visible!=true&&peizhi.IP!="")
                {
                    addre = peizhi.IP;
                    this.Visible = true;
                    Console.WriteLine("窗体关闭：" + addre);
                }
        }  
    }
}